package com.rd.student.jike.class2.lihongming.week731_806.Day0804;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Auther:Heinrich
 * @Date:2023/8/4-08-04-11:35
 * @Description:com.rd.student.jike.class2.lihongming.Day0804
 * @version:1.0
 */
public class Cross3_2 {


    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
        CyclicBarrier cyclicBarrier = new CyclicBarrier(10, new Runnable() {
            @Override
            public void run() {
                System.out.println("已全部通过山洞");
                service.shutdown();
            }
        });
        ThreadCross cross = new ThreadCross(cyclicBarrier);
        service.execute(new Thread(cross, "贾复"));
        service.execute(new Thread(cross, "史弥远"));
        service.execute(new Thread(cross, "张俊"));
        service.execute(new Thread(cross, "刘光世"));
        service.execute(new Thread(cross, "王阳明"));
        service.execute(new Thread(cross, "马周"));
        service.execute(new Thread(cross, "姚崇"));
        service.execute(new Thread(cross, "宋璟"));
        service.execute(new Thread(cross, "贾似道"));
        service.execute(new Thread(cross, "韩世忠"));
    }
}
class ThreadCross implements Runnable{
    CyclicBarrier cyclicBarrier ;

    public ThreadCross(CyclicBarrier cyclicBarrier) {
        this.cyclicBarrier = cyclicBarrier;
    }

    @Override
    public void run() {
        try {
            long start = System.currentTimeMillis();
            Thread.sleep(new Random().nextInt(5000));
            long end = System.currentTimeMillis();
            System.out.println(Thread.currentThread().getName() +
                    "通过山洞"+" 花费了"+(end-start));
            cyclicBarrier.await();
        } catch (InterruptedException | BrokenBarrierException e) {
            throw new RuntimeException(e);
        }
    }
}
